package com.financial.business.yspay.utils;

import java.beans.PropertyDescriptor;
import java.lang.reflect.Method;
import java.lang.reflect.Modifier;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

import org.apache.commons.lang.StringUtils;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.FatalBeanException;
/**
 * @Author WANGNING
 * @Email wyn20140226@aliyun.com
 * @Description //字段是否为空校验工具类，并返回提示
 * @Date 2019/11/11 11:16
 */
public class ValidateUtils {
    //整个类都校验
    public static List<String> validateProperty(Object validateObj) {
        return validateProperty(validateObj,(String[])null);
    }
    //类中的某些字段不校验
    public static List<String> validateProperty(Object validateObj, String... ignoreProperties) {
        PropertyDescriptor[] targetPds = BeanUtils.getPropertyDescriptors(validateObj.getClass());
        List<String> ignoreList = (ignoreProperties != null ? Arrays.asList(ignoreProperties) : null);
        List<String> errList = new ArrayList<>();
        for (PropertyDescriptor targetPd : targetPds) {
            Method readMethod = targetPd.getReadMethod();
            if (readMethod != null && (ignoreList == null || !ignoreList.contains(targetPd.getName()))) {
                try {
                    if (!Modifier.isPublic(readMethod.getDeclaringClass().getModifiers())) {
                        readMethod.setAccessible(true);
                    }
                    Object value = readMethod.invoke(validateObj);
                    if (value instanceof String) {
                        if (StringUtils.isEmpty((String) value)) {
                            errList.add("请求的字段中的 " + targetPd.getName() + "不能为空");
                            continue;
                        }
                    }
                   if (value == null) {
                        errList.add(validateObj.getClass().getSimpleName() + "中的" + targetPd.getName() + "不能为空");
                    }
                } catch (Throwable ex) {
                    throw new FatalBeanException(
                            "Could not copy property '" + targetPd.getName() + "' from source to target", ex);
                }
            }
        }
        return errList;
    }
/*
    public static void main(String[] args) {
        YsWeChatPayDTO ysWeChatPayDTO =new YsWeChatPayDTO();
        ysWeChatPayDTO.setOut_trade_no("29384092384023");
        ysWeChatPayDTO.setPay_fee(new BigDecimal("2"));
        ysWeChatPayDTO.setPay_id("2343214");
        ysWeChatPayDTO.setPay_type("1");
        ysWeChatPayDTO.setStore_no("32423423");
        ysWeChatPayDTO.setSub_openid("");
        ysWeChatPayDTO.setSubject("");
        ysWeChatPayDTO.setTotal_amount(new BigDecimal("0"));
        List<String> ysWeChatPay =ValidateUtils.validateProperty(ysWeChatPayDTO);
        ApiResult apiResult=ApiResult.failure(ysWeChatPay);
        System.out.println(apiResult);

    }*/
}
